import { Button, List, DatePicker, NavBar, Popup, Dialog, Toast } from "antd-mobile";
import classNames from "classnames";
import styles from "./index.module.scss";
import { useRef, useState } from "react";
import { useInitState } from "@/hooks";
import { fetchEditProfile, fetchProfile, fetchUpdatePhoto, clearUserInfo } from "@/store/modules/userSlice";
import EditInput from "./components/EditInput";
import EditList from "./components/EditList";
import dayjs from 'dayjs';
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
const Item = List.Item;

const ProfileEdit = () => {
  const { name, intro, gender, birthday, photo } = useInitState(
    fetchProfile,
    "user",
    "profile"
  );
  type InputPopup = {
    type: InputType;
    value: string;
    visible: boolean;
  };
  const navigate = useNavigate();
  //编辑昵称弹框显示与隐藏
  const [inputPopup, setInputPopup] = useState<InputPopup>({
    type: "",
    value: "",
    visible: false,
  });
  //关闭修改昵称弹框
  const popupClose = () => {
    setInputPopup({ type: "", value: "", visible: false });
  };
  const popupOpen = (type: InputType, value: string) => {
    setInputPopup({ type, value, visible: true });
  };
  //修改用户性别或头像
  type ListPopup = {
    type: ListType;
    visible: boolean;
  };
  const [listPopup, setListPopup] = useState<ListPopup>({
    type: "",
    visible: false,
  });
  //打开修改性别或头像弹框
  const listPopupOpen = (type: ListType) => {
    setListPopup({
      type,
      visible: true,
    });
  };
  //关闭修改性别或头像弹框
  const listPopupClose = () => {
    setListPopup({
      type: "",
      visible: false,
    });
  };
  //选择文件ref
  const fileRef = useRef<HTMLInputElement>(null);
  //选择生日
  let [showBirth, setShowBirth] = useState(false);
  //选择头像
  const photoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) return;
    let formData = new FormData();
    formData.append("photo", e.target.files[0]);
    dispatch(fetchUpdatePhoto(formData));
    Toast.show({
      content: '更新成功',
      duration: 800,
    });
    popupClose();
    listPopupClose();
  };
  const dispatch = useDispatch()
  // 编辑个人信息
  const onUpdateProfile = async (type: EditType, value: string) => {
    if(type === "photo" && value === "local") {
      fileRef.current?.click();
    } else {
      await dispatch(fetchEditProfile({ [type]: value }));
      Toast.show({
        content: '更新成功',
        duration: 800,
      });
      popupClose();
      listPopupClose();
    }
  }
  //退出登录
  const logoutFn = () => {
    Dialog.show({
      content: "亲,确认退出吗?",
      title: "温馨提示",
      closeOnAction: true,
      closeOnMaskClick: true,
      actions: [
        [
          {
            key: "cancel",
            text: "取消",
            style: {
              color: "#999",
            },
          },
          {
            key: "delete",
            text: "确认",
            onClick: () => {
              dispatch(clearUserInfo());
              // 退回个人信息页面会重定向到登录页面
              navigate(-1);
            },
          },
        ],
      ],
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          className="navBar"
          onBack={() => { navigate(-1); }}
          // style={{
          //   '--border-bottom': '1px solid #F0F0F0'
          // }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              onClick={() => listPopupOpen("photo")}
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      photo || "http://toutiao.itheima.net/images/user_head.jpg"
                    }
                    alt=""
                  />
                </span>
              }
              arrow
            >
              头像
            </Item>
            <Item arrow extra={name} onClick={() => popupOpen("name", name)}>
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span className={classNames("intro", "normal")}>
                  {intro ?? "未填写"}
                </span>
              }
              onClick={() => popupOpen("intro", intro ?? "")}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={gender + "" === "0" ? "男" : "女"}
              onClick={() => listPopupOpen("gender")}
            >
              性别
            </Item>
            <Item arrow extra={birthday} onClick={() => setShowBirth(true)}>
              生日
            </Item>
          </List>

          <DatePicker
            style={{ width: "94%" }}
            visible={showBirth}
            value={new Date(birthday)}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            onConfirm={(val) => {
              const date = dayjs(val).format("YYYY-MM-DD");
              onUpdateProfile("birthday", date);
            }}
            onClose={() => setShowBirth(false)}
          />
          <input
            ref={fileRef}
            type="file"
            hidden
            onChange={(e) => photoChange(e)}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={logoutFn}>
            退出登录
          </Button>
        </div>
      </div>

      {/* 编辑昵称或简介弹出层 */}
      <Popup visible={inputPopup.visible} position="right" destroyOnClose>
        <EditInput
          type={inputPopup.type}
          value={inputPopup.value}
          onClose={popupClose}
          onUpdateProfile={onUpdateProfile}
        />
      </Popup>
      {/* 修改性别或头像弹出层 */}
      <Popup
        visible={listPopup.visible}
        destroyOnClose
        onMaskClick={() => {
          listPopupClose();
        }}
      >
        <EditList
          listPopupClose={listPopupClose}
          type={listPopup.type}
          onUpdateProfile={onUpdateProfile}
        />
      </Popup>
    </div>
  );
};

export default ProfileEdit;
